import { decode, encode } from '@msgpack/msgpack';

/**
 * @description base64解码
 * @param base64 base64字符串
 * @returns Uint8Array
 */
export function base64decode(base64: string) {
  // 1. 判断base64是否为空
  if (base64 === undefined) {
    return;
  }

  // 2. Base64解码
  const binaryString = window.atob(base64);

  // 3. 转为Uint8Array
  const uint8Array = new Uint8Array(binaryString.length);
  for (let i = 0; i < binaryString.length; i++) {
    // eslint-disable-next-line unicorn/prefer-code-point
    uint8Array[i] = binaryString.charCodeAt(i);
  }
  // 4. MsgPack解码
  const decoded = decode(uint8Array);
  return decoded;
}

/**
 * @description base64加密
 * @param data 需要加密的数据
 * @returns base64字符串
 */
export function base64encryption(data: any) {
  return btoa(
    // eslint-disable-next-line unicorn/prefer-code-point
    String.fromCharCode(...Object.values(encode(data))),
  );
}
